<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="10" :lg="11" :md="12" :sm="24">
            <a-form-item :label="$t('汇总时间')">
              <a-date-picker
                 :show-time="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"
                valueFormat="YYYY-MM-DD HH:mm:ss"
                :placeholder="$t('请选择开始时间')"
                class="query-group-cust"
                v-model="queryParam.bTime"
              ></a-date-picker>
              <span class="query-group-split-cust"></span>
              <a-date-picker
                 :show-time="{ defaultValue: moment('23:59:59', 'HH:mm:ss') }"
                valueFormat="YYYY-MM-DD HH:mm:ss"
                :placeholder="$t('请选择结束时间')"
                class="query-group-cust"
                v-model="queryParam.eTime"
              ></a-date-picker>
            </a-form-item>
          </a-col>

          <a-col :xl="5" :lg="6" :md="7" :sm="24">
            <a-form-item :label="$t('仓库')">
              <a-tree-select
                allowClear
                v-model="queryParam.goodsStorage"
                style="width: 100%"
                :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
                :tree-data="storeData"
                :search-placeholder="$t('请选择')"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="8" :lg="9" :md="10" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">{{$t('查询')}}</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">{{$t('重置')}}</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? $t('收起') : $t('展开') }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a>
              <a-button type="primary" @click="weekQuery" style="margin-left: 8px">{{ $t('本周') }}</a-button>
              <a-button type="primary" @click="monthQuery" style="margin-left: 8px">{{ $t('本月') }}</a-button>
              <a-button type="primary" @click="yearQuery" style="margin-left: 8px">{{ $t('本年') }}</a-button>
              <a-button type="primary" :loading="exloading" style="margin-left: 8px" @click="handleExportXls($t('进销存报表'))" v-has="'InventoryChangeReportController:export'">{{
                $t('导出')
              }}</a-button>
            </span>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :xl="5" :lg="6" :md="7" :sm="24">
              <a-form-item :label="$t('选择分类')">
                <a-tree-select
                  v-model="queryParam.goodsKind"
                  style="width: 100%"
                  :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
                  :tree-data="treeData"
                  :search-placeholder="$t('请选择')"
                />
              </a-form-item>
            </a-col>
            <a-col :xl="5" :lg="6" :md="7" :sm="24">
              <a-form-item :label="$t('商品')">
                <a-input :placeholder="$t('请输入商品编码/名称/条码')" v-model="queryParam.goodsInfo" />
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item>
                <a-checkbox v-model="queryParam.zeroAfter">{{ $t('显示期末数量为0的商品') }}</a-checkbox>
              </a-form-item>
            </a-col>
          </template>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->
    <!-- table区域-begin -->
    <div>
      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        class="j-table-force-nowrap"
        :scroll="{ x: true }"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :customRow="customRow"
        @change="handleTableChange"
      >
        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="openAmount" slot-scope="text">
          <div>{{isPriceDecimal?text.toFixed(4):text.toFixed(0)}}</div>
        </template>
        <template slot="caiPrice" slot-scope="text">
          <div>{{isPriceDecimal?text.toFixed(4):text.toFixed(0)}}</div>
        </template>
        <template slot="otherInPrice" slot-scope="text">
          <div>{{isPriceDecimal?text.toFixed(4):text.toFixed(0)}}</div>
        </template>
        <template slot="allotInPrice" slot-scope="text">
          <div>{{isPriceDecimal?text.toFixed(4):text.toFixed(0)}}</div>
        </template>
        <template slot="pdInPrice" slot-scope="text">
          <div>{{isPriceDecimal?text.toFixed(4):text.toFixed(0)}}</div>
        </template>
        <template slot="salePrice" slot-scope="text">
          <div>{{isPriceDecimal?text.toFixed(4):text.toFixed(0)}}</div>
        </template>
        <template slot="allotOutPrice" slot-scope="text">
          <div>{{isPriceDecimal?text.toFixed(4):text.toFixed(0)}}</div>
        </template>
        <template slot="pdOutPrice" slot-scope="text">
          <div>{{isPriceDecimal?text.toFixed(4):text.toFixed(0)}}</div>
        </template>
        <template slot="fanPrice" slot-scope="text">
          <div>{{isPriceDecimal?text.toFixed(4):text.toFixed(0)}}</div>
        </template>
        <template slot="otherOutPrice" slot-scope="text">
          <div>{{isPriceDecimal?text.toFixed(4):text.toFixed(0)}}</div>
        </template>
        <template slot="afterAmount" slot-scope="text">
          <div>{{isPriceDecimal?text.toFixed(4):text.toFixed(0)}}</div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic">{{ $t('无图片') }}</span>
          <a-popover v-else trigger="hover">
            <template slot="content">
              <img :src="getImgView(text)" width="240px" />
            </template>
            <img
              :src="getImgView(text)"
              height="25px"
              alt=""
              style="max-width: 80px; font-size: 12px; font-style: italic"
            />
          </a-popover>
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic">{{ $t('无文件') }}</span>
          <a-button v-else :ghost="true" type="primary" icon="download" size="small" @click="downloadFile(text)">{{
            $t('下载')
          }}</a-button>
        </template>
        <span slot="action" slot-scope="text, record">
          <a @click="handleDetail(record)">{{ $t('详情') }}</a>
        </span>
      </a-table>
    </div>
  </a-card>
</template>

<script>
import moment from 'moment'
import '@/assets/less/TableExpand.less'
import { getAction, getFileAccessHttpUrl } from '@/api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { initDictOptions } from '@/components/dict/JDictSelectUtil'
export default {
  name: 'PurchaseSalesAndInventoryReport',
  mixins: [JeecgListMixin],
  components: {},
  data() {
    return {
      moment,
      description: '进销存报表页面',
      isPriceDecimal: true,
      // 表头
      columns: [
        {
          title: this.$t('仓库'),
          align: 'center',
          dataIndex: 'storeName',
          customCell: (r, i) => {
            return {
              style: {
                textAlign: 'left',
              },
            }
          },
        },
        {
          title: this.$t('编码'),
          align: 'center',
          dataIndex: 'goodsCode',
          customCell: (r, i) => {
            return {
              style: {
                textAlign: 'left',
              },
            }
          },
        },
        {
          title: this.$t('名称'),
          align: 'center',
          dataIndex: 'goodsName',
          customCell: (r, i) => {
            return {
              style: {
                textAlign: 'left',
              },
            }
          },
        },
        {
          title: this.$t('商品图片'),
          align: 'center',
          dataIndex: 'picture',
          scopedSlots: { customRender: 'imgSlot' },
        },
        {
          title: this.$t('成本'),
          align: 'center',
          dataIndex: 'cost',
          customRender: (t, r) => {
            if (!t) {
              t = 0
            }
            t = t.toFixed(2);
            if(r.goodsCode != '合计'){
              return t
            }
            return ''
          },
          customCell: (r, i) => {
            return {
              style: {
                textAlign: 'right',
              },
            }
          }
        },
        {
          title: this.$t('分类'),
          align: 'center',
          dataIndex: 'kindName',
          customCell: (r, i) => {
            return {
              style: {
                textAlign: 'left',
              },
            }
          },
        },
        {
          title: this.$t('期初'),
          align: 'center',
          children: [
            {
              title: this.$t('期初数量'),
              align: 'center',
              dataIndex: 'openNum',
              customCell: (r, i) => {
                return {
                  style: {
                    textAlign: 'right',
                  },
                }
              },
              customRender: (text, r) => {
                return text.toFixed(2);
              }

            },
            {
              title: this.$t('期初金额'),
              align: 'center',
              dataIndex: 'openAmount',
              customCell: (r, i) => {
                return {
                  style: {
                    textAlign: 'right',
                  },
                }
              },
              scopedSlots: { customRender: 'openAmount' },
            },
          ],
        },
        {
          title: this.$t('入库'),
          align: 'center',
          children: [
            {
              title: this.$t('采购数量'),
              align: 'center',
              dataIndex: 'caiNum',
              customCell: (r, i) => {
                return {
                  style: {
                    textAlign: 'right',
                  },
                }
              },
            },
            {
              title: this.$t('采购金额'),
              align: 'center',
              dataIndex: 'caiPrice',
              customCell: (r, i) => {
                return {
                  style: {
                    textAlign: 'right',
                  },
                }
              },
              scopedSlots: { customRender: 'caiPrice' },
            },
            {
              title: this.$t('其他入数量'),
              align: 'center',
              dataIndex: 'otherInNum',
              customCell: (r, i) => {
                return {
                  style: {
                    textAlign: 'right',
                  },
                }
              },
            },
            {
              title: this.$t('其他入金额'),
              align: 'center',
              dataIndex: 'otherInPrice',
              customCell: (r, i) => {
                return {
                  style: {
                    textAlign: 'right',
                  },
                }
              },
              scopedSlots: { customRender: 'otherInPrice' },
            },
            {
              title: this.$t('调拨入数量'),
              align: 'center',
              dataIndex: 'allotInNum',
              customCell: (r, i) => {
                return {
                  style: {
                    textAlign: 'right',
                  },
                }
              },
            },
            {
              title: this.$t('调拨入金额'),
              align: 'center',
              dataIndex: 'allotInPrice',
              customCell: (r, i) => {
                return {
                  style: {
                    textAlign: 'right',
                  },
                }
              },
              scopedSlots: { customRender: 'allotInPrice' },
            },
            {
              title: this.$t('盘点入数量'),
              align: 'center',
              dataIndex: 'pdInNum',
              customCell: (r, i) => {
                return {
                  style: {
                    textAlign: 'right',
                  },
                }
              },
            },
            {
              title: this.$t('盘点入金额'),
              align: 'center',
              dataIndex: 'pdInPrice',
              customCell: (r, i) => {
                return {
                  style: {
                    textAlign: 'right',
                  },
                }
              },
              scopedSlots: { customRender: 'pdInPrice' },
            },
          ],
        },
        {
          title: this.$t('出库'),
          align: 'center',
          children: [
            {
              title: this.$t('销售数量'),
              align: 'center',
              dataIndex: 'saleNum',
              customCell: (r, i) => {
                return {
                  style: {
                    textAlign: 'right',
                  },
                }
              },
            },
            {
              title: this.$t('销售金额'),
              align: 'center',
              dataIndex: 'salePrice',
              customCell: (r, i) => {
                return {
                  style: {
                    textAlign: 'right',
                  },
                }
              },
              scopedSlots: { customRender: 'salePrice' },
            },
            {
              title: this.$t('调拨出数量'),
              align: 'center',
              dataIndex: 'allotOutNum',
              customCell: (r, i) => {
                return {
                  style: {
                    textAlign: 'right',
                  },
                }
              },
            },
            {
              title: this.$t('调拨出金额'),
              align: 'center',
              dataIndex: 'allotOutPrice',
              customCell: (r, i) => {
                return {
                  style: {
                    textAlign: 'right',
                  },
                }
              },
              scopedSlots: { customRender: 'allotOutPrice' },
            },
            {
              title: this.$t('盘点出数量'),
              align: 'center',
              dataIndex: 'pdOutNum',
              customCell: (r, i) => {
                return {
                  style: {
                    textAlign: 'right',
                  },
                }
              },
            },
            {
              title: this.$t('盘点出金额'),
              align: 'center',
              dataIndex: 'pdOutPrice',
              customCell: (r, i) => {
                return {
                  style: {
                    textAlign: 'right',
                  },
                }
              },
              scopedSlots: { customRender: 'pdOutPrice' },
            },
            {
              title: this.$t('返货数量'),
              align: 'center',
              dataIndex: 'fanNum',
              customCell: (r, i) => {
                return {
                  style: {
                    textAlign: 'right',
                  },
                }
              },
            },
            {
              title: this.$t('返货金额'),
              align: 'center',
              dataIndex: 'fanPrice',
              customCell: (r, i) => {
                return {
                  style: {
                    textAlign: 'right',
                  },
                }
              },
              scopedSlots: { customRender: 'fanPrice' },
            },
            {
              title: this.$t('其他出库数量'),
              align: 'center',
              dataIndex: 'otherOutNum',
              customCell: (r, i) => {
                return {
                  style: {
                    textAlign: 'right',
                  },
                }
              },
            },
            {
              title: this.$t('其他出库金额'),
              align: 'center',
              dataIndex: 'otherOutPrice',
              customCell: (r, i) => {
                return {
                  style: {
                    textAlign: 'right',
                  },
                }
              },
              scopedSlots: { customRender: 'otherOutPrice' },
            },
          ],
        },
        {
          title: this.$t('期末'),
          align: 'center',
          children: [
            {
              title: this.$t('期末数量'),
              align: 'center',
              dataIndex: 'afterNum',
              customCell: (r, i) => {
                return {
                  style: {
                    textAlign: 'right',
                  },
                }
              },
            },
            {
              title: this.$t('期末金额'),
              align: 'center',
              dataIndex: 'afterAmount',
              customCell: (r, i) => {
                return {
                  style: {
                    textAlign: 'right',
                  },
                }
              },
              scopedSlots: { customRender: 'afterAmount' },
            },
          ],
        },
      ],
      url: {
        list: '/report/goods/inventoryChange/list',
        exportXlsUrl: '/report/goods/inventoryChange/export',
      },
      isCustom: true,
      storageList: [],
      treeData: [],
      queryParam: {
        bTime: moment().format('YYYY-MM-DD 00:00:00'),
        eTime: moment().format('YYYY-MM-DD 23:59:59'),
        goodsStorage: '',
        goodsKind: '',
        zeroAfter: true
      },
      isorter: {
        column: 'goodsCode',
        order: 'desc',
      },
      storeData: [],
    }
  },
  async created() {
    this.isPriceDecimal=await this.getRule()
  },
  methods: {
    getRule(){
      return new Promise(resolve=>{
        getAction('/bis/bisSysParameter/list', { name: 'isPriceDecimal' }).then((res) => {
          let value=true
          if (res.success&&res.result.total > 0) {
            let isPriceDecimal = res.result.records[0]
            value = isPriceDecimal.ivalue ? true : false
          }
          resolve(value)
        })
      })
    },
    getImgView(text) {
      if (text && text.indexOf(',') > 0) {
        text = text.substring(0, text.indexOf(','))
      }
      return getFileAccessHttpUrl(text)
    },
    initDictConfig() {
      initDictOptions('bis_order_goods.form').then((res) => {
        if (res.success) {
          this.storageList = res.result
          this.storageList.unshift({ value: '', title: this.$t('全部') })
        }
      })
      // getAction('/goods/bisGoodsStore/list').then((res) => {
      //   if (res.success) {
      //     let records = res.result.records
      //     this.storageList = records.map((rds) => {
      //       let dtl = {
      //         value: rds.id,
      //         title: rds.name,
      //       }
      //       return dtl
      //     })
      //     this.storageList.unshift({ value: '', title: this.$t('全部') })
      //   }
      // })
      this.select()
      this.getStoreList()
      console.log(this.storeData)
      this.searchQuery()
    },
    getStoreList(item) {
      let that = this
      let storeList = []
      let param = {}
      param.pageNo = 1
      param.pageSize = 9999
      param.column = 'id'
      param.order = 'DESC'
      getAction('/goods/bisGoodsStore/rootList', param).then((res) => {
        if (res.success) {
          that.allChildKind = []
          storeList = res.result.records
          if (storeList.length > 0) {
            storeList.forEach((col) => {
              col.key = '' + col.id
              col.value = '' + col.id
              col.title = '' + col.name
              col.id = '' + col.id
              col.pid = '' + col.pid
              col.hasChild = '' + col.hasChild
              if (col.hasChild != '0') {
                that.getHasChildStore(col)
              }
            })
            that.storeData = that.getDataByResult(storeList)
            that.storeData.unshift({ key: '', id: '', value:'', title: this.$t('全部') })
          }
        }
      })
    },
    getHasChildStore(store) {
      let that = this
      let query = {}
      query.pageNo = 1
      query.pageSize = 9999
      query.pid = store.id
      getAction('/goods/bisGoodsStore/rootList', query).then((res) => {
        if (res.success) {
          if (res.result.records.length > 0) {
            res.result.records.forEach((col) => {
              col.key = '' + col.id
              col.value = '' + col.id
              col.title = '' + col.name
              col.pid = '' + col.pid
              col.id = '' + col.id
              col.hasChild = '' + col.hasChild
              if (col.hasChild != '0') {
                that.getHasChildStore(col)
              }
            })
            store.children = that.getDataByResult(res.result.records)
            that.storeData = [...that.storeData]
          }
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    select() {
      let that = this
      let param = {}
      param.pageNo = 1
      param.pageSize = 9999
      param.column = 'sort'
      param.order = 'asc'
      getAction('/goods/bisGoodsKind/rootList', param)
        .then((res) => {
          if (res.success) {
            that.allChildKind = []
            if (res.result.records.length > 0) {
              res.result.records.forEach((col) => {
                col.key = '' + col.id
                col.value = '' + col.id
                col.title = '' + col.name
                col.id = '' + col.id
                col.pid = '' + col.pid
                col.hasChild = '' + col.hasChild
                if (col.hasChild != '0') {
                  that.getHasChild(col)
                }
              })
              that.treeData = that.getDataByResult(res.result.records)
              that.treeData.unshift({ key: '', id: '', value: '', title: this.$t('全部') })
            } else {
              that.treeData = []
            }
          } else {
            that.$alert(res.message, this.$t('提示'), {
              confirmButtonText: this.$t('确定'),
              callback: (action) => {},
            })
          }
        })
        .catch((error) => {
          console.log(error)
        })
    },
    getHasChild(record) {
      let that = this
      let query = {}
      query.pageNo = 1
      query.pageSize = 9999
      query.pid = record.id
      getAction('/goods/bisGoodsKind/rootList', query)
        .then((res) => {
          if (res.success) {
            if (res.result.records.length > 0) {
              res.result.records.forEach((col) => {
                col.key = '' + col.id
                col.value = '' + col.id
                col.title = '' + col.name
                col.pid = '' + col.pid
                col.id = '' + col.id
                col.hasChild = '' + col.hasChild
                if (col.hasChild != '0') {
                  that.getHasChild(col)
                }
              })
              record.children = that.getDataByResult(res.result.records)
              that.treeData = [...that.treeData]
            }
          } else {
            that.$message.warning(res.message)
          }
        })
        .catch((error) => {
          console.log(error)
        })
    },
    getDataByResult(result) {
      let that = this
      return result.map((item) => {
        if (item.hasChild == 0 && item.key != '0') {
          that.allChildKind.push(item.key)
        }
        return item
      })
    },
    searchReset() {
      let that = this
      that.queryParam = {
        bTime: moment().format('YYYY-MM-DD 00:00:00'),
        eTime: moment().format('YYYY-MM-DD 23:59:59'),
        goodsStorage: '',
        goodsKind: '',
        zeroAfter: true
      }
      that.loadData(1)
    },
    weekQuery(){
      let that = this
      that.queryParam.bTime= moment().startOf('week').format('YYYY-MM-DD 00:00:00')
      that.queryParam.eTime= moment().format('YYYY-MM-DD 23:59:59')
      that.loadData(1)
    },
    monthQuery(){
      let that = this
      that.queryParam.bTime= moment().startOf('month').format('YYYY-MM-DD 00:00:00')
      that.queryParam.eTime= moment().format('YYYY-MM-DD 23:59:59')
      that.loadData(1)
    },
    yearQuery(){
      let that = this
      that.queryParam.bTime= moment().startOf('year').format('YYYY-MM-DD 00:00:00')
      that.queryParam.eTime= moment().format('YYYY-MM-DD 23:59:59')
      that.loadData(1)
    },
    customRow(r, i) {
      return {
        style: {
          fontWeight: r.goodsCode == this.$t('合计') ? 700 : 400,
        },
      }
    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>